/**
 * 权限管理 Composable
 * 提供权限检查功能
 */
import { ref, computed } from 'vue'
import api from '../services/api'

// 全局权限状态
const permissions = ref([])
const isAdmin = ref(false)
const roles = ref([])
const permissionsLoaded = ref(false)

export function usePermissions() {
  /**
   * 加载当前用户权限
   */
  const loadPermissions = async () => {
    try {
      const response = await api.getCurrentUserPermissions()
      permissions.value = response.permissions || []
      isAdmin.value = response.is_superuser || false
      roles.value = response.roles || []
      permissionsLoaded.value = true
      console.log('用户权限加载成功:', permissions.value)
      console.log('是否管理员:', isAdmin.value)
      console.log('用户角色:', roles.value)
    } catch (error) {
      console.error('加载权限失败:', error)
      permissions.value = []
      isAdmin.value = false
      roles.value = []
      permissionsLoaded.value = false
    }
  }

  /**
   * 检查是否拥有指定权限
   * @param {string} permission - 权限代码，如 'host.view'
   * @returns {boolean}
   */
  const hasPermission = (permission) => {
    if (!permission) return true
    if (isAdmin.value) return true
    if (permissions.value.includes('*')) return true
    return permissions.value.includes(permission)
  }

  /**
   * 检查是否拥有任一指定权限
   * @param {string[]} permissionList - 权限代码数组
   * @returns {boolean}
   */
  const hasAnyPermission = (...permissionList) => {
    if (permissionList.length === 0) return true
    if (isAdmin.value) return true
    if (permissions.value.includes('*')) return true
    return permissionList.some(p => permissions.value.includes(p))
  }

  /**
   * 检查是否拥有所有指定权限
   * @param {string[]} permissionList - 权限代码数组
   * @returns {boolean}
   */
  const hasAllPermissions = (...permissionList) => {
    if (permissionList.length === 0) return true
    if (isAdmin.value) return true
    if (permissions.value.includes('*')) return true
    return permissionList.every(p => permissions.value.includes(p))
  }

  /**
   * 检查是否拥有某个模块的任意权限
   * @param {string} module - 模块名称，如 'host', 'user'
   * @returns {boolean}
   */
  const hasModulePermission = (module) => {
    if (isAdmin.value) return true
    if (permissions.value.includes('*')) return true
    return permissions.value.some(p => p.startsWith(`${module}.`))
  }

  /**
   * 获取用户所有权限
   * @returns {string[]}
   */
  const getAllPermissions = () => {
    return [...permissions.value]
  }

  /**
   * 获取用户所有角色
   * @returns {Object[]}
   */
  const getAllRoles = () => {
    return [...roles.value]
  }

  /**
   * 清除权限缓存（用于退出登录）
   */
  const clearPermissions = () => {
    permissions.value = []
    isAdmin.value = false
    roles.value = []
    permissionsLoaded.value = false
  }

  return {
    // 状态
    permissions: computed(() => permissions.value),
    isAdmin: computed(() => isAdmin.value),
    roles: computed(() => roles.value),
    permissionsLoaded: computed(() => permissionsLoaded.value),
    
    // 方法
    loadPermissions,
    hasPermission,
    hasAnyPermission,
    hasAllPermissions,
    hasModulePermission,
    getAllPermissions,
    getAllRoles,
    clearPermissions
  }
}

// 导出权限代码常量
export const PERMISSIONS = {
  // 主机管理
  HOST_VIEW: 'host.view',
  HOST_ADD: 'host.add',
  HOST_EDIT: 'host.edit',
  HOST_DELETE: 'host.delete',
  HOST_SSH: 'host.ssh',
  
  // 用户管理
  USER_VIEW: 'user.view',
  USER_ADD: 'user.add',
  USER_EDIT: 'user.edit',
  USER_DELETE: 'user.delete',
  
  // Ansible管理
  ANSIBLE_VIEW: 'ansible.view',
  ANSIBLE_EXECUTE: 'ansible.execute',
  ANSIBLE_CONFIG: 'ansible.config',
  
  // 系统管理
  SYSTEM_AUDIT: 'system.audit',
  SYSTEM_CONFIG: 'system.config',
  SYSTEM_MONITOR: 'system.monitor'
}
